package com.ruge.ruge_novel_front.controller;

import com.ruge.ruge_novel_front.dao.RugeNovelDao;
import com.ruge.ruge_novel_front.dao.RugeNovelRuleDao;
import com.ruge.ruge_novel_front.model.RugeNovelChapterModel;
import com.ruge.ruge_novel_front.model.RugeNovelModel;
import com.ruge.ruge_novel_front.model.RugeNovelRuleModel;
import com.ruge.ruge_novel_front.tool.CrawlerTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.*;

@RestController
public class RugeNovelController {
    @Autowired
    private RugeNovelDao novelDao;
    @Autowired
    private RugeNovelRuleDao rugeNovelRuleDao;
    @Autowired
    private CrawlerTool tool;

    @GetMapping(value = "/novel/{keyword}")
    public Map<String, Object> get(@PathVariable("keyword") String keyword) {
        Map<String, Object> result = new HashMap<>();
        List<RugeNovelModel> list = novelDao.findByNovelNameLike("%" + keyword.trim() + "%");
        if (list.isEmpty()) {
            List<RugeNovelRuleModel> rugeNovelRuleModels = rugeNovelRuleDao.findAll();
            if (rugeNovelRuleModels.isEmpty()) {
                RugeNovelRuleModel save = rugeNovelRuleDao.saveAndFlush(new RugeNovelRuleModel());
                rugeNovelRuleModels.add(save);
            }
            Map<String, String> map = new HashMap<>();
            map.put("key", keyword);
            list = tool.getRugeNovel(rugeNovelRuleModels, map);
        }
        for (int i = 0; i < list.size(); i++) {
            Optional<RugeNovelRuleModel> ruleDaoById = rugeNovelRuleDao.findById(list.get(i).getSourceId());
            if (ruleDaoById.isPresent()) {
                list.get(i).setSourceName(ruleDaoById.get().getSourceName());
                list.get(i).setNovelDesc(StringUtils.abbreviate(list.get(i).getNovelDesc(),50));
            }
        }
        result.put("code", 0);
        result.put("msg", "");
        result.put("count", list.size());
        result.put("data", list);
        return result;
    }

    /**
     * @param id 小说的id
     * @return小说的章节列表
     */
    @GetMapping("/chapterList/{id}")
    public Map<String, Object> getChapter(@PathVariable("id") int id) {
        Map<String, Object> result = new HashMap<>();
        List<RugeNovelChapterModel> list = tool.getrugeChapter(id);
        result.put("code", 0);
        result.put("msg", "");
        result.put("count", list.size());
        result.put("data", list);
        return result;
    }

    @GetMapping("/contextDetail/{chapterId}/{type}")
    public RugeNovelChapterModel getContext(
            @PathVariable("chapterId") Integer chapterId,
            @PathVariable("type") Integer type) {
        return tool.getrugeContext(chapterId, type);
    }
}
